import tkinter as tk
from tkinter import ttk, messagebox
import re
import requests

class NamingToolApp:
    def __init__(self, root):
        self.root = root
        self.root.title("变量命名工具 v1.0")
        # API配置
        self.headers = {
            "accept": "application/json, text/plain, */*",
            "accept-language": "zh-CN,zh;q=0.9,en-GB;q=0.8,en;q=0.7,en-US;q=0.6,pt;q=0.5",
            "authorization": "A7ruPoZYM4BAXeNqzPI2lw2AaGVHK3IY",
            "content-type": "application/json;charset=UTF-8",
            "origin": "https://tool.h234.cn",
            "referer": "https://tool.h234.cn/",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0"
        }
        self.api_url = "https://api.osuu.net/rcode"
        self.root.geometry("800x650")
        self.root.resizable(True, True)
        
        # 设置样式
        self.style = ttk.Style()
        self.style.configure("TLabel", font=("SimHei", 10))
        self.style.configure("TButton", font=("SimHei", 10))
        self.style.configure("TRadiobutton", font=("SimHei", 10))
        
        # 创建主框架
        self.main_frame = ttk.Frame(root, padding="30")
        self.main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 标题
        title_label = ttk.Label(self.main_frame, text="变量命名转换工具", font=("SimHei", 16, "bold"))
        title_label.pack(pady=(0, 25))
        
        # 变量名输入
        ttk.Label(self.main_frame, text="输入原始变量名:", font=("SimHei", 11)).pack(anchor=tk.W, pady=(15, 5))
        
        self.input_var = tk.StringVar()
        input_entry = ttk.Entry(self.main_frame, textvariable=self.input_var, font=("SimHei", 11), width=50)
        input_entry.pack(fill=tk.X, pady=(0, 20))
        input_entry.focus()
        
        # 确定按钮
        button_frame = ttk.Frame(self.main_frame)
        button_frame.pack(pady=(10, 25))
        
        ttk.Button(button_frame, text="获取命名结果", command=self.convert_naming, width=15).pack(side=tk.LEFT, padx=10)
        ttk.Button(button_frame, text="清除输入", command=self.clear_input, width=15).pack(side=tk.LEFT, padx=10)
        
        # 结果显示区域
        ttk.Label(self.main_frame, text="命名结果:", font=("SimHei", 11)).pack(anchor=tk.W, pady=(25, 5))
        
        # 创建结果框架
        result_frame = ttk.Frame(self.main_frame)
        result_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 10), padx=5)
        
        # 结果变量
        self.results = {
            "constant": tk.StringVar(value=""),
            "pascal_case": tk.StringVar(value=""),
            "camel_case": tk.StringVar(value=""),
            "snake_case": tk.StringVar(value=""),
            "prefix_case": tk.StringVar(value=""),
            "project_name": tk.StringVar(value="")
        }
        
        # 结果标签和输入框
        naming_labels = [
            ("常量:", "constant"),
            ("大驼峰(类命名):", "pascal_case"),
            ("小驼峰(方法命名):", "camel_case"),
            ("下划线:", "snake_case"),
            ("前下划线:", "prefix_case"),
            ("项目名:", "project_name")
        ]
        
        for i, (label_text, var_name) in enumerate(naming_labels):
            # 创建框架容纳标签和输入框
            row_frame = ttk.Frame(result_frame)
            row_frame.pack(fill=tk.X, pady=3)
            
            # 标签
            ttk.Label(row_frame, text=label_text, width=20).pack(side=tk.LEFT)
            
            # 结果输入框
            entry = ttk.Entry(row_frame, textvariable=self.results[var_name], state="readonly", font=("SimHei", 11))
            entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
            
            # 复制按钮
            ttk.Button(row_frame, text="复制", command=lambda v=var_name: self.copy_specific_result(v)).pack(side=tk.LEFT, padx=5)
        
        # 全部复制按钮
        ttk.Button(self.main_frame, text="复制全部结果", command=self.copy_all_results).pack(pady=(15, 15))
    
    def convert_naming(self):
        input_text = self.input_var.get().strip()
        if not input_text:
            messagebox.showwarning("警告", "请输入变量名")
            return
        
        try:
            # 发送API请求
            data = {"query": input_text}
            response = requests.post(self.api_url, headers=self.headers, json=data)
            response.raise_for_status()
            result = response.json()
            # 创建命名规则字典
            naming_rules = {}
            # 安全提取数据并处理可能的结构变化
            try:
                # 检查是否存在data字段
                if 'data' not in result:
                    raise KeyError("API响应缺少'data'字段")
                
                for category in result['data']:
                    # 检查每个分类是否包含items
                    if 'items' not in category:
                        print(f"警告: 分类'{category.get('name', '未知')}'缺少'items'字段")
                        continue
                    
                    for item in category['items']:
                        # 确保每个item包含key和value
                        if 'key' in item and 'value' in item:
                            naming_rules[item['key']] = item['value']
                        else:
                            print(f"警告: 无效的item结构: {item}")
            except Exception as e:
                print(f"解析API响应时出错: {str(e)}")
                messagebox.showwarning("数据解析警告", f"解析API响应时出错: {str(e)}")
            
            # 定义需要提取的命名规则及其默认值
            required_rules = {
                "常量": "未找到常量规则",
                "大驼峰(类命名)": "未找到大驼峰(类命名)规则",
                "小驼峰(方法命名)": "未找到小驼峰(方法命名)规则",
                "下划线": "未找到下划线规则",
                "前下划线": "未找到前下划线规则",
                "项目名": "未找到项目名规则"
            }
            
            # 更新所有结果变量并检查缺失的规则
            missing_rules = []
            for rule_name, default_value in required_rules.items():
                value = naming_rules.get(rule_name, default_value)
                if value == default_value:
                    missing_rules.append(rule_name)
                
                # 根据规则名更新对应的结果变量
                if rule_name == "常量":
                    self.results["constant"].set(value)
                elif rule_name == "大驼峰(类命名)":
                    self.results["pascal_case"].set(value)
                elif rule_name == "小驼峰(方法命名)":
                    self.results["camel_case"].set(value)
                elif rule_name == "下划线":
                    self.results["snake_case"].set(value)
                elif rule_name == "前下划线":
                    self.results["prefix_case"].set(value)
                elif rule_name == "项目名":
                    self.results["project_name"].set(value)
            
            # 如果有缺失的规则，显示警告
            if missing_rules:
                warning_msg = f"以下命名规则未找到:\n{', '.join(missing_rules)}"
                print(warning_msg)
                messagebox.showwarning("规则缺失", warning_msg)
        except requests.exceptions.RequestException as e:
            messagebox.showerror("API错误", f"请求失败: {str(e)}")
        except KeyError as e:
            messagebox.showerror("数据错误", f"缺少字段: {str(e)}")
        except Exception as e:
            messagebox.showerror("错误", f"转换失败: {str(e)}")
    
    def to_camel_case(self, text):
        # 处理不同格式的输入
        if '_' in text:
            words = text.split('_')
        elif '-' in text:
            words = text.split('-')
        else:
            # 假设是 PascalCase 或 camelCase
            words = re.findall(r'[A-Z]?[a-z]+|[A-Z]+(?=[A-Z][a-z]|\\b)', text)
        
        if not words:
            return text
            
        # 第一个单词小写，其余单词首字母大写
        return words[0].lower() + ''.join(word.capitalize() for word in words[1:])
    
    def to_pascal_case(self, text):
        # 处理不同格式的输入
        if '_' in text:
            words = text.split('_')
        elif '-' in text:
            words = text.split('-')
        else:
            # 假设是 camelCase
            words = re.findall(r'[A-Z]?[a-z]+|[A-Z]+(?=[A-Z][a-z]|\\b)', text)
        
        if not words:
            return text
            
        # 所有单词首字母大写
        return ''.join(word.capitalize() for word in words)
    
    def to_snake_case(self, text):
        # 处理 camelCase 和 PascalCase
        if re.match(r'^[a-zA-Z]+$', text):
            # 添加下划线并转为小写
            text = re.sub(r'(?<!^)(?=[A-Z])', '_', text).lower()
        
        # 处理可能的连字符
        text = text.replace('-', '_')
        
        # 替换多个下划线为单个下划线
        text = re.sub(r'_+', '_', text)
        
        # 移除首尾下划线
        return text.strip('_')
    
    def to_kebab_case(self, text):
        # 先转换为蛇形命名，再替换下划线为连字符
        snake_case = self.to_snake_case(text)
        return snake_case.replace('_', '-')
    
    def copy_specific_result(self, var_name):
        result = self.results[var_name].get()
        if result and result != "未找到":
            self.root.clipboard_clear()
            self.root.clipboard_append(result)
            messagebox.showinfo("成功", "结果已复制到剪贴板")
        else:
            messagebox.showwarning("警告", "没有可复制的结果")
    
    def copy_all_results(self):
        result_lines = []
        naming_labels = [
            "常量:",
            "大驼峰(类命名):",
            "小驼峰(方法命名):",
            "下划线:",
            "前下划线:",
            "项目名:"
        ]
        
        for i, var_name in enumerate(self.results.keys()):
            value = self.results[var_name].get()
            if value and value != "未找到":
                result_lines.append(f"{naming_labels[i]} {value}")
        
        if result_lines:
            all_text = "\n".join(result_lines)
            self.root.clipboard_clear()
            self.root.clipboard_append(all_text)
            messagebox.showinfo("成功", f"已复制 {len(result_lines)} 项结果到剪贴板")
        else:
            messagebox.showwarning("警告", "没有可复制的结果")
    
    def clear_input(self):
        self.input_var.set("")
        for var in self.results.values():
            var.set("")

if __name__ == "__main__":
    root = tk.Tk()
    app = NamingToolApp(root)
    root.mainloop()